//
//  SWBasketEditingViewController.swift
//  ChildStory
//
//  Created by linhan on 2017/1/13.
//  Copyright © 2017年 Aiya. All rights reserved.
//

import Foundation
import UIKit
class SWBasketEditingViewController: SWBaseViewController,SWBookPageEditorDelegate
{
    //未完成的页面
    private var _incompletenessPages:[SWPage] = []
    private var _index:Int = 0
    
    private var _pageEditor:SWBookPageEditor?
    private var _countLabel:UILabel = UILabel()
    private var _titleLabel:UILabel = UILabel()
    
    lazy private var _complementLabel:UILabel = UILabel()
    lazy private var _complementStatusBar:UIView = UIView()
    lazy private var _incompletenessView = UIView()
    lazy private var _completenessView = UIView()
    
    private var _sortBtn:UIButton = UIButton(type: .system)
    private var _nextBtn:UIButton = UIButton(type: .system)
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
    }
    
    private func setup()
    {
        automaticallyAdjustsScrollViewInsets = false
        view.backgroundColor = UIColor(white: 0.95, alpha: 1)
        
        //TopView
        let lastY = createTopToolbar(y: navigationBarBottom)
        let bottomBarHeight:CGFloat = createBottomBar()
        
        //翻页
        createPageView(lastY, bottomMargin:bottomBarHeight)
        
        //不完整的页面
        let manager = SWTransactionManager.sharedManager()
        manager.pages.sort(by: {$0.page.photoImportedTime < $1.page.photoImportedTime})
        let pages:[SWPage] = manager.pages.map({$0.page})
        let incompletenessPages:[SWPage] = pages.filter({!$0.completeness})
        _incompletenessCount = incompletenessPages.count
        _incompletenessPages = incompletenessPages
        
        if incompletenessPages.count > 0
        {
            createComplementStatusBar()
            _inComplementStatus = true
            
            _pageEditor?.reloadData(pages: incompletenessPages, index:0)
            pageShowed(index: 0)
        }
        else
        {
            _pageEditor?.reloadData(pages: pages, index:0)
            pageShowed(index: 0)
        }
        
        SWNotificationCenter.addObserver(self, selector: #selector(pageCompletedManualNotification(_:)), name: NotificationName.PageCompletedManual, object: nil)
    }
    
    
    
    
    private var _incompletenessCount:Int = 0{
        didSet{
            let incompleteness:Bool = _incompletenessCount > 0
            
            _incompletenessView.isHidden = !incompleteness
            _completenessView.isHidden = incompleteness
            _complementLabel.text = "剩余  \(_incompletenessCount)  页"
        }
    }
    
    //是否处于补全状态
    private var _inComplementStatus:Bool = false{
        didSet{
            _complementStatusBar.isHidden = !_inComplementStatus
        }
    }
    
    private func createTopToolbar(y:CGFloat) -> CGFloat
    {
        let toolbar:UIView = UIView()
        toolbar.frame = CGRectMake(0, y, view.width, 40)
        toolbar.backgroundColor = UIColor(white: 0.97, alpha: 1)
        view.addSubview(toolbar)
        
        _countLabel.frame = CGRectMake(view.width - 90, 0, 90, toolbar.height)
        _countLabel.textAlignment = .right
        _countLabel.textColor = UIColor.darkGray
        toolbar.addSubview(_countLabel)
        
        let titleLabelWidth:CGFloat = _countLabel.x
        _titleLabel.frame = CGRectMake(0, 0, titleLabelWidth, toolbar.height)
        _titleLabel.textColor = UIColor.darkGray
        toolbar.addSubview(_titleLabel)
        
        return toolbar.bottom
    }
    
    private func createBottomBar() -> CGFloat
    {
        let height:CGFloat = 30
        let bar:UIView = UIView()
        bar.frame = CGRectMake(0, view.height - height, view.width, height)
        view.addSubview(bar)
        
        let sortBtnWidth:CGFloat = 100
        _sortBtn.backgroundColor = UIColor.darkGray
        _sortBtn.setTitle("调整顺序", for: .normal)
        _sortBtn.addTarget(self, action: #selector(sortBtnTapped), for: .touchUpInside)
        _sortBtn.frame = CGRectMake(0, 0, sortBtnWidth, 30)
        bar.addSubview(_sortBtn)
        
        _nextBtn.backgroundColor = UIColor.lightGray
        _nextBtn.setTitle("3/3 选择款式", for: .normal)
        _nextBtn.addTarget(self, action: #selector(nextBtnTapped), for: .touchUpInside)
        _nextBtn.frame = CGRectMake(sortBtnWidth, 0, bar.width - sortBtnWidth, 30)
        bar.addSubview(_nextBtn)
        
        return height
    }
    
    private func createComplementStatusBar()
    {
        let height:CGFloat = 30
        _complementStatusBar.backgroundColor = UIColor(white: 0.95, alpha: 1)
        _complementStatusBar.frame = CGRectMake(0, view.height - height, view.width, height)
        view.addSubview(_complementStatusBar)
        
        //未补齐完成
        _incompletenessView.frame = _complementStatusBar.bounds
        _complementStatusBar.addSubview(_incompletenessView)
        
        let label:UILabel = UILabel()
        label.text = "补齐缺失照片"
        label.font = UIFont.systemFont(ofSize: 14)
        label.sizeToFit()
        _incompletenessView.addSubview(label)
        
        let labelWidth:CGFloat = 150
        _complementLabel.font = UIFont.systemFont(ofSize: 14)
        _complementLabel.textAlignment = .right
        _complementLabel.textColor = UIColor.darkGray
        _complementLabel.frame = CGRectMake(view.width - labelWidth, 0, labelWidth, _complementStatusBar.height)
        _incompletenessView.addSubview(_complementLabel)
        
        //已补齐完成
        _completenessView.frame = _complementStatusBar.bounds
        _complementStatusBar.addSubview(_completenessView)
        
        let completeBtn = UIButton(type: .system)
        completeBtn.backgroundColor = UIColor.lightGray
        completeBtn.setTitle("照片补好了", for: .normal)
        completeBtn.frame = _completenessView.bounds
        completeBtn.addTarget(self, action: #selector(completeBtnTapped), for: .touchUpInside)
        _completenessView.addSubview(completeBtn)
        
    }
    
    //翻页组件
    private func createPageView(_ lastY:CGFloat, bottomMargin:CGFloat)
    {
        let PageViewInsets:UIEdgeInsets = UIEdgeInsetsMake(lastY, 0, bottomMargin, 0)
        let ContainerSize = CGSizeMake(view.width - PageViewInsets.left - PageViewInsets.right, view.height - PageViewInsets.top - PageViewInsets.bottom)
        let BookFullPageSize = SW.Config.BookSinglePageSize
        let scale:CGFloat = ViewUtil.getAdaptiveScale(BookFullPageSize.width, targetH: BookFullPageSize.height, containerW: ContainerSize.width, containerH: ContainerSize.height)
        let PageViewSize = CGSizeMake(BookFullPageSize.width * scale, BookFullPageSize.height * scale)
        let PageViewX:CGFloat = PageViewInsets.left + (ContainerSize.width - PageViewSize.width) * 0.5
        let PageViewY:CGFloat = PageViewInsets.top + (ContainerSize.height - PageViewSize.height) * 0.5
        let PageViewRect = CGRectMake(PageViewX, PageViewY, PageViewSize.width, PageViewSize.height)
        
        
        let pageEditor:SWBookPageEditor = SWBookPageEditor(frame:PageViewRect)
        pageEditor.delegate = self
        view.addSubview(pageEditor)
        _pageEditor = pageEditor
    }
    
    func bookPageEditor(editor:SWBookPageEditor, didScrollToIndex index: Int)
    {
        _index = index
        pageShowed(index: index)
    }
    
    private func pageShowed(index: Int)
    {
        let incompleteness:Bool = _inComplementStatus && _incompletenessPages.count > 0
        let pages:[SWPage] = incompleteness ? _incompletenessPages : SWTransactionManager.sharedManager().pages.map({$0.page})
        if let page = pages.valueAt(index)
        {
            _titleLabel.text = page.title ?? ""
            _countLabel.text = "\(index + 1)/\(pages.count)"
        }
    }
    
    @objc private func nextBtnTapped()
    {
        let pages:[SWPage] = SWTransactionManager.sharedManager().pages.map({$0.page})
        if let index = pages.index(where: {!$0.completeness})
        {
            _pageEditor?.jumbIndex(index: index, animated: true)
            SVProgressHUD.showError(withStatus: "第\(index)页未补齐")
        }
        else
        {
            navigationController?.pushViewController(SWCheckoutViewController(), animated: true)
        }
    }
    
    @objc private func sortBtnTapped()
    {
        let viewController = SWBasketPageSortViewController()
        viewController.sortedCompleteCallback = {[weak self] in
            let pages:[SWPage] = SWTransactionManager.sharedManager().pages.map({$0.page})
            self?._pageEditor?.reloadData(pages: pages, index:0)
        }
        let navigationController = SWBaseNavigationController(rootViewController: viewController)
        present(navigationController, animated: true, completion: nil)
    }
    
    @objc private func pageCompletedManualNotification(_ notification:Notification)
    {
        print("pageCompletedManualNotification")
        //自动翻到下一页
        if _incompletenessPages.count > 0
        {
            let incompletenessPages:[SWPage] = _incompletenessPages.filter({!$0.completeness})
            _incompletenessCount = incompletenessPages.count
            if let index = _incompletenessPages.index(where: {!$0.completeness}),_inComplementStatus
            {
                _pageEditor?.jumbIndex(index: index, animated: true)
            }
            else
            {
                
            }
        }
    }
    
    @objc private func completeBtnTapped()
    {
        _inComplementStatus = false
        _incompletenessPages = []
        _index = 0
        let pages:[SWPage] = SWTransactionManager.sharedManager().pages.map({$0.page})
        _pageEditor?.reloadData(pages: pages, index: 0)
    }
    
    
    
    
}
